<?php
/*
* Products rating
* for Ajax
* author: mr.Trieu
*/
require './source/class/class_core.php';
$discuz = & discuz_core::instance();
$discuz->init();

$aResponse['error'] = false;
$aResponse['message'] = '';
$aResponse['server'] = '';
	
if(isset($_POST['action'])){
	if(htmlentities($_POST['action'], ENT_QUOTES, 'UTF-8') == 'rating'){
		/*
		* vars
		*/
		$id = intval($_POST['idBox']);
		$rate = floatval($_POST['rate']);
		$time = time();

		// Check uid & last time vote
		$res = DB::query('SELECT vote_uid, vote_time
						  FROM ' . DB::table('shop_products') . '
						  WHERE pid = ' . $id);
		while ($row = DB::fetch($res)){
			$userID = $row['vote_uid'];
			$voteTime = $row['vote_time'];
		}

		// if request successful
		if ($_G['uid'] && $_G['uid'] != $userID)
			$success = true;
		else
			$success = false;

		// json datas send to the js file
		if($success){
			/*
			* Cap nhat rating product vao mysql
			*/
			$Query = 'UPDATE ' . DB::table('shop_products') . '
					  SET vote = vote + 1, total_vote = total_vote + ' . $rate . ',
					  	  vote_time = ' . $time . ',
						  vote_uid = ' . $_G['uid'] . '
					  WHERE pid = ' . $id;
			DB::query($Query);

			$aResponse['message'] .= 'Cảm ơn bạn đã bình chọn cho sản phẩm này :)';
			echo json_encode($aResponse);
		}else{
			$aResponse['error'] = true;
			$aResponse['message'] .= 'Xin lỗi,<br />Hiện tại bạn đang là người cuối bình chọn cho sản phẩm này.';
			echo json_encode($aResponse);
		}
	}else{
		$aResponse['error'] = true;
		$aResponse['message'] .= '"action" post data not equal to \'rating\'';
		echo json_encode($aResponse);
	}
}else{
	$aResponse['error'] = true;
	$aResponse['message'] .= '$_POST[\'action\'] not found';
	echo json_encode($aResponse);
}